package pkg

import (
	"errors"
	"fmt"
	"sync"
)

type PortPool struct {
	lock     sync.Mutex
	Pool     []int
	BasePort int
}

func (p *PortPool) Fill(num int) *PortPool {

	p.lock.Lock()

	last := p.BasePort
	poolLen := len(p.Pool)

	if poolLen != 0 {
		last = p.Pool[poolLen-1]
	}

	for i := 0; i < num; i++ {
		p.Pool = append(p.Pool, last+i)
	}

	return p
}

func (p *PortPool) GetPort(index int) (int, error) {

	if index < 0 || index >= len(p.Pool) {
		return 0, errors.New("切片越界")
	}

	return p.Pool[index], nil

}

func (p *PortPool) PortString(index int) (string, error) {

	port, err := p.GetPort(index)

	if err != nil {
		return "", errors.New("切片越界")
	}

	return fmt.Sprintf(":%d", port), nil

}
